//
//  TollStationViewController.m
//  Runone
//
//  Created by runone02 on 16/11/14.
//  Copyright © 2016年 runone. All rights reserved.
//

#import "TollStationViewController.h"
#import "requestStation.h"
#import "Define.h"
#import "AppLocalManager.h"
#import "StationDetailInfo.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import "SDWebImageManager.h"
#import "UIImageView+WebCache.h"
#import "RequestHelper.h"
#import "StationModel.h"
#import "AppDelegate.h"
#import "BigMapViewController.h"
#import "SVProgressHUD.h"
#import "StationDetailInfo.h"
#import "MJRefresh.h"
#import "MJExtension.h"
#import "AppDelegate.h"
#import "HighwayMergeInfoModel.h"
#import "MergeJsonModel.h"
#import "EnlargeMapViewController.h"

#import "HighwayMergeRoadRecordModel.h"
#import "HighWayRoadRecordDirectionInfoModel.h"
#import "HighwayMergeInfoModel.h"
#import "MergeJsonModel.h"
#import "LineMergeJsonModel.h"
#import "CustomCallOutView.h"
#import "CustomAnnotationView.h"
#import "ROPicScrollView.h"
#import "StationMonirotViewController.h"
#import "UIViewController+Loading.h"

@interface TollStationViewController ()<MAMapViewDelegate,UIScrollViewDelegate,UIPopoverPresentationControllerDelegate,ROPicScrollViewDataSource, ROPicScrollViewDelegate>
// ***************************** -控件- *****************************

@property (weak, nonatomic) IBOutlet UIScrollView *backScrollView;
@property (weak, nonatomic) IBOutlet MAMapView    *mapview;
@property (weak, nonatomic) IBOutlet UIImageView  *iconImg;
@property (weak, nonatomic) IBOutlet UILabel      *stationNameL;
@property (weak, nonatomic) IBOutlet UILabel      *pileNOL;
@property (weak, nonatomic) IBOutlet UILabel      *inCountL;
@property (weak, nonatomic) IBOutlet UILabel      *outCountL;
@property (weak, nonatomic) IBOutlet UILabel      *ETCIncountL;
@property (weak, nonatomic) IBOutlet UILabel      *ETCOutCountL;
@property (weak, nonatomic) IBOutlet UILabel      *leaderL;
@property (weak, nonatomic) IBOutlet UILabel      *contactNOL;
@property (weak, nonatomic) IBOutlet UIView       *scroolContainView;

@property (weak, nonatomic) IBOutlet UIView *imageView;
@property (strong, nonatomic) ROPicScrollView *imageScrollView;

@property (weak, nonatomic) IBOutlet UIButton *lastBtn;
@property (weak, nonatomic) IBOutlet UIButton *nextBtn;

// ***************************** -返回的收费站模型- *****************************
@property (nonatomic,strong) StationDetailInfo *stationM;

// ***************************** -数组- *****************************
@property (nonatomic, strong) NSMutableArray *pointarray; //标注数组
// ***************************** -记录当前收费站的下标- *****************************
@property (nonatomic, assign) NSInteger recordStationIndex;

// **************************** -上下切换的模型- ******************************
@property (nonatomic, strong) HighwayMergeInfoModel *lastModel;
@property (nonatomic, strong) HighwayMergeInfoModel *nextModel;

// **************************** -保存所有收费站模型- ******************************
@property (nonatomic, strong) NSMutableArray *stationsArray;

@property (nonatomic, strong) NSMutableArray *picArray;


@end

@implementation TollStationViewController

#pragma    --------收费站详情

#pragma mark -按钮点击
//放大地图
- (IBAction)enlargeBtnClick:(id)sender {
    EnlargeMapViewController *vc = [[EnlargeMapViewController alloc] init];
    vc.la   = _mergeModel.mergeJson.Latitude ;
    vc.lo   = _mergeModel.mergeJson.Longitude;
    vc.type = AllIconTypeStation;
    [self presentViewController:vc animated:YES completion:nil];
}
//视频
- (IBAction)trafficBtnClick:(UIButton *)btn {
    btn.selected = !btn.selected;
    if (btn.selected) {
        _mapview.showTraffic=YES;
    } else {
        _mapview.showTraffic=NO;
    }
}

- (IBAction)lastStationBtn:(id)sender {
//    NSLog(@"上一个收费站");
    _recordStationIndex -= 1;
    if (_recordStationIndex != 0) {
        HighwayMergeInfoModel *Model = _stationsArray[_recordStationIndex];
        _mergeModel                  = Model;
        _lastModel                   = _stationsArray[_recordStationIndex - 1];
        _nextModel                   = _stationsArray[_recordStationIndex + 1];
        _nextBtn.hidden = NO;
        [self requstStationInfo];
        [self setBtnTitle];
    } else {
        HighwayMergeInfoModel *Model = _stationsArray[_recordStationIndex];
        _mergeModel                  = Model;
        _nextModel                   = _stationsArray[_recordStationIndex + 1];
        _lastBtn.hidden    = YES;
        [self requstStationInfo];
        [self setBtnTitle];
    }
}
- (IBAction)nextStationBtn:(id)sender {
//    NSLog(@"下一个收费站");
    _recordStationIndex += 1;
    if (_recordStationIndex == _stationsArray.count - 1) {
        HighwayMergeInfoModel *Model  = _stationsArray[_recordStationIndex];
        _mergeModel                   = Model;
        _lastModel                    = _stationsArray[_recordStationIndex - 1];
        [self requstStationInfo];
        [self setBtnTitle];
        
    }else {
        HighwayMergeInfoModel *Model = _stationsArray[_recordStationIndex];
        _mergeModel                  = Model;
        _lastModel                   = _stationsArray[_recordStationIndex - 1];
        _nextModel                   = _stationsArray[_recordStationIndex + 1];
        _lastBtn.hidden = NO;
        [self requstStationInfo];
        [self setBtnTitle];
    }
}

//视频
- (IBAction)tollStationMonitorBtn:(id)sender {
    StationMonirotViewController *stationMonitorVC = [[StationMonirotViewController alloc] init];
    stationMonitorVC.stationM         = _stationM;
    stationMonitorVC.currentRoadModel = _currentRoadModel;
    [self.navigationController pushViewController:stationMonitorVC animated:YES];
}


#pragma mark - 设置上 下 按钮标题
- (void) setBtnTitle {
//    AppDelegate *myDelegate  = (AppDelegate*) [UIApplication sharedApplication].delegate;
    if (_recordStationIndex == 0 && _stationsArray.count > 1 ) {
        _nextModel = _stationsArray[_recordStationIndex + 1];
        _lastBtn.hidden = YES;
        [_nextBtn setTitle:_nextModel.mergeJson.TollStationName forState:UIControlStateNormal];
    }else if (_recordStationIndex == 0 && _stationsArray.count == 1) {
        _lastBtn.hidden = YES;
        _nextBtn.hidden = YES;
    }else if (_recordStationIndex == _stationsArray.count - 1) {
        _nextBtn.hidden = YES;
        _lastModel = _stationsArray[_recordStationIndex - 1];
        [_lastBtn setTitle:_lastModel.mergeJson.TollStationName forState:UIControlStateNormal];
    }else {
        _lastModel = _stationsArray[_recordStationIndex - 1];
        _nextModel = _stationsArray[_recordStationIndex + 1];
        [_lastBtn setTitle:_lastModel.mergeJson.TollStationName forState:UIControlStateNormal];
        [_nextBtn setTitle:_nextModel.mergeJson.TollStationName forState:UIControlStateNormal];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self showLoadingView];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.backScrollView.bounces               = NO;
    _lastModel =  [[HighwayMergeInfoModel alloc] init];
    _nextModel =  [[HighwayMergeInfoModel alloc] init];
    _recordStationIndex = 0;
    [self setArray];
    [self setUpNaviBar];
    [self loadMapView];
    [self configImageScrollView];
    [self requstStationInfo];
    [self getAllStationModel];
    [self judgeNowStationPositionONArray];
    [self setBtnTitle];
    
}
#pragma mark - 设置导航栏
- (void) setUpNaviBar {
    UILabel *label                = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 30)];
    label.text                    = @"收费站详情";
    label.textAlignment           = NSTextAlignmentCenter;
    label.textColor               = [UIColor whiteColor];
    self.navigationItem.titleView = label;
}

-(void) configImageScrollView {
    ROPicScrollViewConfiguration *pcv = [ROPicScrollViewConfiguration defaultConfiguration];
    
    pcv.pageAlignment = PageContolAlignmentCenter;
    pcv.itemConfiguration.contentMode =  UIViewContentModeScaleToFill;
    
    ROPicScrollView *ps = [ROPicScrollView picScrollViewWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width - 16, 200) withConfiguration:pcv withDataSource:self];
    
    ps.delegate = self;
 
    _imageScrollView = ps;
}

#pragma mark - 获得所有收费站
- (void) getAllStationModel {
    for (HighwayMergeInfoModel *stationModel in _currentRoadModel.mergeInfoList) {
        if (stationModel.mergeType == 1) {
            [_stationsArray addObject:stationModel];
        }
    }
}
#pragma mark - 判断当前收费站在数组中的位置
- (void) judgeNowStationPositionONArray {
    for (int i = 0; i <_stationsArray.count; i++ ) {
        HighwayMergeInfoModel *Model = _stationsArray[i];
        if ([Model.mergeName isEqualToString:_mergeModel.mergeName]) {
            _recordStationIndex = i;
            break;
        }
    }
    if (_recordStationIndex == 0 && _stationsArray.count > 1) {
        _nextModel = _stationsArray[_recordStationIndex + 1];
    }else if (_recordStationIndex == 0 && _stationsArray.count == 1){
        _nextModel = nil;
    }
    else if (_recordStationIndex == _stationsArray.count - 1) {
        _lastModel = _stationsArray[_recordStationIndex - 1];
    } else {
        _lastModel = _stationsArray[_recordStationIndex - 1];
        _nextModel = _stationsArray[_recordStationIndex + 1];
    }
}


- (void) setArray {
    _pointarray    = [[NSMutableArray alloc] init];
    _stationsArray = [[NSMutableArray alloc] init];
    _picArray      = [[NSMutableArray alloc] init];
}
#pragma mark -刷新数据
//http://192.168.1.200:8090/api/DownloadResource?systemCode=GuangleHighway&resType=2&resName=%E5%9D%AA%E7%9F%B3%E8%A5%BF-%E5%A4%96%E5%B9%BF%E5%9C%BA.jpg&extra=%E5%9D%AA%E7%9F%B3%E8%A5%BF%E6%94%B6%E8%B4%B9%E7%AB%99

//_RoadPicUrl	__NSCFString *	@"http://192.168.1.200:8090/api/DownloadResource?systemCode=GuangleHighway&resType=1&resName=广乐高速.png&extra=主线"	0x00000001741dfef0	0x00000001741dfef0	0x00000001741dfef0
- (void)refreshData {
    NSString *s=@"Bearer ";
    NSString *strone;
    SDWebImageDownloader *sdmanager = [SDWebImageManager sharedManager].imageDownloader;
    if (GETACCESS_TOKEN!=nil) {
       // NSLog(@"%@",GETACCESS_TOKEN);
        strone=[s stringByAppendingString:GETACCESS_TOKEN];
        [sdmanager setValue:strone forHTTPHeaderField:@"Authorization"];
    }
    NSLog(@"%@",[_currentRoadModel.RoadPicUrl mj_url]);
    [_iconImg sd_setImageWithURL:[_currentRoadModel.RoadPicUrl mj_url]];
    _stationNameL.text    = _stationM.TollStationName;
    //广乐特殊的要求，只能写死
    if ([_currentRoadModel.RoadUID isEqualToString:@"8dd13d88-cb02-4471-876b-1dfe39419ee6"]) { //非主线
         _pileNOL.text         = [NSString stringWithFormat:@"%@+%ld",_stationM.PileNo,(long)_stationM.PileDistance];
    } else {
        NSString *LStr  = @"L";
        NSString *LKStr = [LStr stringByAppendingString:_stationM.PileNo];
        _pileNOL.text   = [NSString stringWithFormat:@"%@+%ld",LKStr,(long)_stationM.PileDistance];
    }
    
    _inCountL.text        = [NSString stringWithFormat:@"入口车道:%ld",(long)_stationM.EntranceLaneCount];
    _outCountL.text       = [NSString stringWithFormat:@"出口车道:%ld",(long)_stationM.ExitLaneCount];
    _ETCIncountL.text     = [NSString stringWithFormat:@"ETC入口:%ld",(long)_stationM.ETCEntranceCount];
    _ETCOutCountL.text    = [NSString stringWithFormat:@"ETC出口:%ld",(long)_stationM.ETCExitCount];
    if (_stationM.DutyPersonName) {
        _leaderL.text               = [NSString stringWithFormat:@"值班领导: %@",_stationM.DutyPersonName];
    }else {
        _leaderL.text               = @"值班领导:";
    }
    if (_stationM.MobilePhone) {
        _contactNOL.text        = [NSString stringWithFormat:@"联系电话: %@",_stationM.MobilePhone];
    }else {
        _contactNOL.text            = @"联系电话:";
    }
    //处理返回来的图片
    [_picArray removeAllObjects];
    
    if (_stationM.TollStationPictures.count > 0) {
        for (NSString *obj in _stationM.TollStationPictures) {
            [_picArray addObject:obj];
        }
        [_imageView addSubview:_imageScrollView];
        [_imageScrollView reloadData];           //刷新滚动视图的view
    } else {
        [_imageScrollView removeFromSuperview];
    }
}

#pragma mark - 图片轮播器代理方法
- (NSUInteger)numberOfItemsInPicScrollView:(ROPicScrollView *)picScrollView {
    return _picArray.count;
}

- (void)picScrollView:(ROPicScrollView *)picScrollView needUpdateItem:(ROPicItem *)item atIndex:(NSInteger)index {
    NSString *urlStr = [_picArray objectAtIndex:index];
//    NSURL *picUrl = [NSURL URLWithString:urlStr];
    NSLog(@"%@",[urlStr mj_url]);
   [item.imageView sd_setImageWithURL:[urlStr mj_url] placeholderImage:nil];
}

#pragma mark - 请求
- (void) requstStationInfo {
 
    RequestHelper *requestHelper=[[RequestHelper alloc] init];
    RequestGinsengModel *getHighwayModel = [[RequestGinsengModel alloc] init];
    getHighwayModel.URL                  = GetDeviceDataURL;
    getHighwayModel.DataValue            = [self DataValueStr];
    getHighwayModel.UpdatedTime          = @"2000-1-1 12:00:00";
    getHighwayModel.SystemCode           = DefaultSystemCode;
    getHighwayModel.MethodName           = @"GetTollStationDetailInfo";
    requestHelper.block = ^(RequestOutginseng *requestOutginseng,id dataValueModel){
        NSLog(@"%@",requestOutginseng.DataValue);
        [self hideLoadingView];
        _stationM = [StationDetailInfo mj_objectWithKeyValues:requestOutginseng.DataValue];
        [self loadAnnotation];
        [self refreshData];
    };
    [requestHelper RequestGinsengModel:getHighwayModel andPushController:self];
}

#pragma mark - 加载地图标注
- (void) loadAnnotation {
    [_mapview removeAnnotations:_pointarray];
    [_pointarray removeAllObjects];
    MAPointAnnotation *pointAnnotation = [[MAPointAnnotation alloc] init];
    CGFloat latitude           = _stationM.Latitude ;
    CGFloat longitude          = _stationM.Longitude;
    pointAnnotation.coordinate = CLLocationCoordinate2DMake(latitude,longitude);
    
    CLLocationCoordinate2D centerCoordinate = CLLocationCoordinate2DMake(latitude, longitude);
    MACoordinateSpan  span                  = MACoordinateSpanMake(0.070622, 0.056355);
    MACoordinateRegion region               = MACoordinateRegionMake(centerCoordinate, span);
    _mapview.region                         = region;
    [_mapview setCenterCoordinate:centerCoordinate animated:NO];
    
    [_pointarray addObject:pointAnnotation];
    [_mapview addAnnotation:pointAnnotation];
}

#pragma mark - 地图
-(void)loadMapView {
    [AMapServices sharedServices].apiKey = GETGAODEPAIKEY;
    _mapview.delegate        = self;
    _mapview.showsCompass    = NO;
    _mapview.showsScale      = NO;

}

#pragma mark -地图代理
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation {
    if ([annotation isKindOfClass:[MAPointAnnotation class]]) {
        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
        MAPinAnnotationView*annotationView = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        if (annotationView == nil) {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
        }
        annotationView.image = [UIImage imageNamed:@"station_icon"];
        
        annotationView.centerOffset = CGPointMake(0, -annotationView.image.size.height / 2);
        
        return annotationView;
    }
    return nil;
}


#pragma mark - 去掉斜杠
- (NSString *)componentsSeparatedByString:(NSString *)path{
    NSArray *result = [path componentsSeparatedByString:@"\\"];
    path = nil;
    for (NSString *obj in result) {
        if (path==nil) {
            path = obj;
        }else{
            path = [NSString stringWithFormat:@"%@/%@",path,obj];
        }
    }
    return path;
}

-(NSString *)encodeString:(NSString *)string {
    NSString *temp = [[NSString stringWithFormat:@"%@",string] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    return temp;
}

#pragma mark -拼接参数
-(NSString *)DataValueStr {
    NSString *beginstr  = @"[{\"key\":\"TollStationUID\",\"value\":\"";
    NSString *str       = _mergeModel.mergeJson.TollStationUID;
    NSString *endstr    = @"\"}]";
    NSString *temp      = [beginstr stringByAppendingString:str];
    NSString *dataValue = [temp stringByAppendingString:endstr];
    return dataValue;
}


@end
